package com.wx.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wx.pojo.OrderDetail;
import com.wx.pojo.OrderListVO;
import com.wx.pojo.OrderMaster;
import com.wx.pojo.OrderVo;
import com.wx.service.CartService;
import com.wx.service.OrderMasterService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 订单
 * @author gzcadmin
 *
 */
@Controller
@RequestMapping("/orderMaster")
public class OrderMasterController {
	
	@Autowired
	private OrderMasterService orderMasterService;
	
	@Autowired
	private CartService cartService;
	/**
	 * 新建订单
	 * 通过前端传递过来的json字符串，然后
	 * @param orderList
	 * @throws Exception
	 */
	@RequestMapping(value="/create",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>createOrder(@RequestParam(value="orderList")String orderList) throws Exception{
		Map<String,Object>modelMap=new HashMap<>();
		OrderVo orderVO=new OrderVo();
		if(orderList=="" || orderList==null) {
			modelMap.put("errno", 2);//json字符串为空，返回
			return modelMap;
		}
		//转换字符编码，防止乱码
		orderList=new String(orderList.getBytes("ISO8859-1"),"utf-8");
		System.out.println(orderList);
		//解析json字符串，转换为json对象
		JSONObject jsonObject=JSONObject.fromObject(orderList);
		String buyerId=jsonObject.getString("userId");
		String buyerName=jsonObject.getString("realname");
		String buyerPhone=jsonObject.getString("phone");
		String orderNote=jsonObject.getString("beizhu");
		String sourceListString=jsonObject.getString("goodsList");
		
		OrderMaster orderMaster=new OrderMaster();
		orderMaster.setBuyerId(buyerId);
		orderMaster.setBuyerName(buyerName);
		orderMaster.setBuyerPhone(buyerPhone);
		orderMaster.setOrderNote(orderNote);//订单备注信息
//		JSONObject sourceListObject=JSONObject.fromObject(sourceListString);
		JSONArray sourceList=JSONArray.fromObject(sourceListString);
		
		List<OrderDetail> orderDetailList=new ArrayList<>();
		List<Integer> cartIdList=new ArrayList<>();
		//获取订单详细信息
		for(int i=0;i<sourceList.size();i++) {
			OrderDetail orderDetail=new OrderDetail();
			Object obj=sourceList.getJSONObject(i);
			JSONObject source=JSONObject.fromObject(obj);
			//若订单详情是单个物品，直接购买时使用该关键字
			if(source.containsKey("goodsId")) {
				orderDetail.setSourceId(Integer.parseInt(source.getString("goodsId")));
				orderDetail.setSourceName(source.getString("name"));
				orderDetail.setSourceCount(Integer.parseInt(source.getString("number")));
				orderDetail.setSourceIcon(source.getString("pic"));
			}else if(source.containsKey("sourceId")) {
				//若从购物车购买信息，则使用该关键字获取订单中商品的详细信息
				orderDetail.setSourceId(Integer.parseInt(source.getString("sourceId")));
				orderDetail.setSourceName(source.getString("sourceName"));
				orderDetail.setSourceCount(Integer.parseInt(source.getString("sourceCount")));
				orderDetail.setSourceIcon(source.getString("sourceImage"));
				Integer cartId=Integer.parseInt(source.getString("cartId"));
				cartIdList.add(cartId);
			}
			orderDetailList.add(orderDetail);
		}
		
		orderVO.setOrderMaster(orderMaster);
		orderVO.setOrderDetailList(orderDetailList);
		//查询订单信息判断是否插入成功
		String orderId=orderMasterService.createOrderMaster(orderVO);
		if(orderId!=null && orderId!="") {
			System.out.println(orderId);
			if(!cartIdList.isEmpty() && cartIdList.size()>0) {
				for (Integer cartId : cartIdList) {
					cartService.removeSourceBycartId(cartId);
				}
			}
			modelMap.put("orderId", orderId);
			modelMap.put("errno", 0);//提交订单成功
		}else {
			modelMap.put("errno", 1);//提交订单错误
		}
		return modelMap;  
	}
	/**
	 * 查询订单信息通过用户id
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/findOrder",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>findOrder(@RequestParam("userId")String userId ){
		Map<String,Object>modelMap=new HashMap<>();
		System.out.println(userId);
		if(userId==null || userId=="") {
			modelMap.put("errno", 2);//用户id传值错误
			return modelMap;
		}
		List<OrderListVO> orderListVOList = orderMasterService.findOrderByUserId(userId);
		System.out.println(orderListVOList);
		if(orderListVOList==null) {
			modelMap.put("errno",3);//订单为空
			return modelMap;
		}
		if(orderListVOList.isEmpty() || orderListVOList.size()<0) {
			modelMap.put("errno", 1);//查询失败、
			return modelMap;
		}
		modelMap.put("errno", 0);
		modelMap.put("orderListVO", orderListVOList);
		return modelMap;
	}
	
	/**
	 * 取消订单
	 * @return
	 */
	@RequestMapping(value="/removeOrder",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>removeOrder(@RequestParam("orderId")String orderId){
		
		Map<String,Object>modelMap=new HashMap<>();
		if(orderId==null||orderId=="") {
			modelMap.put("ernno", 1);//订单id为空
			return modelMap;
		}
		orderId=orderId.substring(2);
		orderMasterService.removeOrder(orderId);
		modelMap.put("errno", 0);//取消订单成功
		return modelMap;
	}
	/**
	 * 支付
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="/payOrder",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>payOrder(@RequestParam("orderId")String orderId){
		Map<String,Object>modelMap=new HashMap<>();
		if(orderId==null||orderId=="" || orderId=="undefined") {
			modelMap.put("ernno", 1);//订单id为空
			return modelMap;
		}
		orderId=orderId.substring(2);
		Boolean flag=orderMasterService.payOrder(orderId);
		if(flag==true) {
			
			modelMap.put("errno", 0);//支付订单成功
		}else {
			modelMap.put("errno", 2);//订单信息错误
		}
		return modelMap;
	}
	
	/**
	 * 完成服务
	 * 改变订单状态为2
	 * 订单状态  0：代表新下单  1：代表取消订单   2、完成订单
	 */
	@RequestMapping(value="/finishOrder",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>finishOrder(@RequestParam("orderId")String orderId){
		Map<String,Object>modelMap=new HashMap<>();
		if(orderId==null||orderId=="") {
			modelMap.put("ernno", 1);//订单id为空
			return modelMap;
		}
		orderId=orderId.substring(2);
		Boolean flag=orderMasterService.finishOrder(orderId);
		if(flag==true) {
			modelMap.put("errno", 0);//完成订单服务成功
		}else {
			modelMap.put("errno", 2);//订单信息错误
		}
		return modelMap;
	}
	/**
	 * 完成订单信息，修改订单状态
	 * order_status:0：新下单  1；取消订单  2完成订单
	 * 支付状态：0：未支付  1：已支付
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/findOrderFinish",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>findOrderFinish(@RequestParam("userId")String userId ){
		Map<String,Object>modelMap=new HashMap<>();
		System.out.println(userId);
		if(userId==null || userId=="") {
			modelMap.put("errno", 2);//用户id传值错误
			return modelMap;
		}
		List<OrderListVO> orderListVOList = orderMasterService.findOrderFinishByUserId(userId);
		System.out.println(orderListVOList);
		if(orderListVOList==null) {
			modelMap.put("errno",3);//订单为空
			return modelMap;
		}
		if(orderListVOList.isEmpty() || orderListVOList.size()<0) {
			modelMap.put("errno", 1);//查询失败、
			return modelMap;
		}
		modelMap.put("errno", 0);
		modelMap.put("orderListVO", orderListVOList);
		return modelMap;
	}
	
}
